import Taro, { Component } from '@tarojs/taro'
import { View, Button, Text, Input } from '@tarojs/components'
import { AtToast } from "taro-ui"
import { post } from '../../service/api'
import './index.scss'

class PhoneLogin extends Component {
  constructor() {
    super(...arguments)
    this.state = {
      isShowTime: false,
      text: "获取验证码",
      time: 60,
      phone: "",
      code: "",
      isShowToast: false,
      disabled: false,
      msg: "",
      auth: false
    }
  }
  config = {
    navigationBarTitleText: '手机登录',
  }
  async keyCode() {
    const { phone } = this.state, { data } = await post('sms/sendCode', {
      userName: phone
    })
    if (data.code == 0) {
      this.pop('短信已发送成功！')
    } else {
      this.pop(data.msg)
    }
  }
  async Login() {
    const res = await Taro.login();
    const res2 = await Taro.getUserInfo()
    const { phone, code } = this.state, { data } = await post('login', {
      phone,
      code,
      jscode: res.code,
      encryptedData: res2.encryptedData,
      iv: res2.iv
    })
    if (data.code == 0) {
      if (!Taro.setStorageSync('sessionKey') && this.state.auth) Taro.setStorageSync('sessionKey', data.sessionKey);

      if (data.loginStatus && data.loginStatus == 'ok') {

        if (data.isRegister && data.isRegister == 'false') {
          Taro.navigateTo({ url: '/pages/invitationCode/index' })
        } else {
          Taro.switchTab({ url: '/pages/index/index' });
        }
      }
    } else {
      this.pop("验证码输入有误，请重试")
    }
  }
  pop(msg) {
    this.setState({
      isShowToast: true,
      msg: msg
    }, () => {
      setTimeout(() => {
        this.setState({
          isShowToast: false
        })
      }, 1500)
    })
  }
  getPhone(e) {
    let { code } = this.state;
    let disabled = e.detail.value && code
    this.setState({
      phone: e.detail.value,
      disabled: disabled
    })
  }
  getCode(e) {
    let { phone } = this.state;
    let disabled = phone && e.detail.value
    this.setState({
      code: e.detail.value,
      disabled: disabled
    })
  }
  toPagePass() {
    Taro.navigateTo({ url: "/pages/passLogin/index" })
  }
  BtnCode() {
    this.keyCode()
    let timer = null;
    clearInterval(timer)
    this.setState({
      text: '重新获取',
      isShowTime: true
    }, () => {
      let time = 60;
      timer = setInterval(() => {
        time--;
        this.setState({ time })
        if (time == 0) {
          clearInterval(timer)
          time = 60;
          this.setState({
            isShowTime: false
          })
        }
      }, 1500)
    })
  }

  bindGetUserInfo(e) {
    if (e.detail.userInfo) {
      this.setState({
        auth: true
      })
    }
  }
  componentDidMount() {
    this.setState({
      phone: "",
      code: ""
    })
  }
  render() {
    let { text, isShowTime, phone, code, disabled, isShowToast, msg } = this.state;
    return (
      <View className='p-login'>
        <View className="input-box">
          <View className="icon-box">
            <Image className="img1" src={require("../../asset/imgs/sjh.png")} />
          </View>
          <Input className="care-num" value={phone} onInput={this.getPhone} type='number' maxLength='11' placeholder="请输入手机号" placeholder-style="color:#ccc;" />
        </View>
        <View className="input-box">
          <View className="icon-box">
            <Image className="img2" src={require("../../asset/imgs/yzm.png")} />
          </View>
          <Input className="care-num" value={code} onInput={this.getCode} type='number' maxLength='4' placeholder="请输入验证码" placeholder-style="color:#ccc;" />
          <View className="getCode">
            <View class={isShowTime ? "none" : ""} onClick={this.BtnCode.bind(this)}>{text}</View>
            <View class={isShowTime ? "" : "none"}>{time}s</View>
          </View>
        </View>
        <View className="hint">未注册手机验证后即注册</View>
        <View className={disabled ? "confirm-btn-d confirm-btn" : "confirm-btn-d"} onClick={this.Login.bind(this)}>
          <Button open-type="getUserInfo" className="btn" onGetUserInfo={this.bindGetUserInfo.bind(this)}></Button>确定
        </View>
        <View className="toPassLogin" onClick={this.toPagePass}>使用账号密码登录</View>
        <AtToast
          isOpened={isShowToast}
          text={msg}
          duration={2000}
        ></AtToast>
      </View>
    )
  }
}

export default PhoneLogin
